package com.ylfstu.jdbc.dao_.dao;

import com.ylfstu.jdbc.datasource.JdbcUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: Joy_yang
 * @Date: 2022/10/21 12:35
 * 编写BasicDAO，是其他DAO的父类
 */
public class BasicDAO<T> { //泛型指定具体类型

    private QueryRunner qr =  new QueryRunner();

    //开发dml方法，针对任意的表
    public int update(String sql, Object... parameters ) {
        Connection connection = null;
        try {
            connection = JdbcUtilsByDruid.getConnection();
            int update = qr.update(connection, sql, parameters);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e); //将编译异常转成运行异常，抛出
        } finally {
            JdbcUtilsByDruid.close(null, null, connection);
        }
    }

    //返回多个对象(即查询的对象是多行的)，针对任意的表
    /**
     * @param sql:sql语句，可以有？
     * @param clazz: 传入一个类的class对象种类 比如Actor.class
     * @param parameters: 传入？的具体值，可以是多个
     * @return 根据Actor.class 返回对应的 ArrayList 集合
     */
    public List<T> queryMulti(String sql, Class<T> clazz, Object... parameters) {

        Connection connection = null;
        try {
            connection = JdbcUtilsByDruid.getConnection();
            return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtilsByDruid.close(null, null, connection);
        }
    }

    //查询单行结果的通用方法
    public T querySingle(String sql, Class<T> clazz, Object... parameters) {

        Connection connection = null;
        try {
            connection = JdbcUtilsByDruid.getConnection();
            return qr.query(connection, sql, new BeanHandler<T>(clazz), parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtilsByDruid.close(null, null, connection);
        }
    }

    //查询单值的方法
    public Object queryScalar(String sql, Object... parameters) {

        Connection connection = null;
        try {
            connection = JdbcUtilsByDruid.getConnection();
            return qr.query(connection, sql, new ScalarHandler(), parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtilsByDruid.close(null, null, connection);
        }
    }
}
